package com.ncdnapp.core.tracer;

import org.noear.solon.Utils;
import org.slf4j.MDC;

import java.util.function.Consumer;

public class TraceThread extends Thread {
    private Tracer tracer;
    private String logFileName;

    private Runnable delegate;
    private Consumer<Runnable> runner;

    public TraceThread(Runnable delegate) {
        this.delegate = delegate;
        this.tracer = TraceContext.get();
        this.logFileName = MDC.get("logFileName");
    }

    public TraceThread(Runnable delegate, Consumer<Runnable> runner) {
        this.delegate = delegate;
        this.tracer = TraceContext.get();
        this.logFileName = MDC.get("logFileName");
        this.runner = runner;
    }

    @Override
    public void run() {
        TraceContext.start(this.tracer);
        if (!Utils.isBlank(logFileName)) {
            MDC.put("logFileName", logFileName);
        }
        if (runner == null) {
            this.delegate.run();
        } else {
            this.runner.accept(this.delegate);
        }
        TraceContext.end();
    }
}
